package dm.com.dmexamples.image_chooser;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FilenameFilter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import dm.com.dmexamples.R;

import static dm.com.dmexamples.image_chooser.PermissionCheckUtils.REQUEST_STORAGE_READ_ACCESS_PERMISSION;

/**
 * @author Damon.Han
 * @Description: 选择图片activity
 * @date 2016年3月22日 上午9:45:22
 */
public class ImageChooserActivity extends AppCompatActivity implements ListImageDirPopupWindow.OnImageDirSelected, OnClickListener {
    public static final int requestCode = 10000;
    public static final String requestCodeKey = "selectedImgs";
    private View back;
    private Button ok;
    private GridView mGirdView;
    private ProgressDialog mProgressDialog;
    private RelativeLayout mBottomLy;
    private TextView mChooseDir;
    private TextView mImageCount;
    private TextView mToPreview;
    /* 存储文件夹中的图片数量 */
    /* 图片数量最多的文件夹 */
    private File mImgDir;
    private ArrayList<ImagePreviewBean> mAllFiles;//获取所有的-阅览全部图片
    /* 所有的图片 */
    private List<ImagePreviewBean> mImgs;
    private BeanAdapter<ImagePreviewBean> beanAdapter;
    /* 临时的辅助类，用于防止同一个文件夹的多次扫描 */
    private HashSet<String> mDirPaths = new HashSet<String>();
    /* 扫描拿到所有的图片文件夹 */
    private List<ImageFloder> mImageFloders = new ArrayList<ImageFloder>();
    /* 当前文件夹共有多少张图片 */
    private int totalCount = 0;
    private ListImageDirPopupWindow mListImageDirPopupWindow;
    /* 用户选择的图片-存储为图片的完整路径 */
    public static ArrayList<String> mSelectedImage = new ArrayList<String>();
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mProgressDialog.dismiss();
            // 为View绑定数据
            data2View();
            // 初始化展示文件夹的popupWindw
            initListDirPopupWindw();
        }
    };


    private int choosenCount;
    private int maxCount;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.img_chooser_main);
        choosenCount = getIntent().getIntExtra("choosenCount", 0);
        maxCount = getIntent().getIntExtra("maxCount", 0);
        initView();
        ok.setText(String.format(getResources().getString(R.string.choose_pic), choosenCount, maxCount));
        mSelectedImage.clear();
        ArrayList<String> selected = getIntent().getStringArrayListExtra("selected");
        if (selected != null && selected.size() > 0) {
            mSelectedImage.addAll(selected);
        }
        getImages();
        initListener();
        beanAdapter = new BeanAdapter<ImagePreviewBean>(this, R.layout.img_chooser_grid_item) {
            @Override
            public void bindView(View itemV, final int position, final ImagePreviewBean jos) {

                if (mImgs == null) {
                    return;
                }
                final ImagePreviewBean item = mImgs.get(position);

                ViewHolder holder = ViewHolder.getHolder(itemV);
                ViewUtil.bindView(holder.getView(R.id.id_item_image), R.drawable.image_chooser_pictures_no);
                ViewUtil.bindView(holder.getView(R.id.id_item_select), R.drawable.image_chooser_dir_unchecked);
                ViewUtil.bindView(holder.getView(R.id.id_item_image), "file://" + item.url);

                final ImageView mImageView = (ImageView) holder.getView(R.id.id_item_image);
                final ImageView mSelect = (ImageView) holder.getView(R.id.id_item_select);
                final View mLayoutCheck = holder.getView(R.id.mLayoutCheck);

                ViewUtil.bindingImageView(mImageView, "file://" + item.url, false, false);
                mImageView.setColorFilter(Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
                // 设置ImageView的点击事件
                mLayoutCheck.setOnClickListener(new OnClickListener() {
                    // 选择，则将图片变暗，反之则反之
                    @Override
                    public void onClick(View v) {
                        itemImgSelected(item.url, mImageView, mSelect, position);
                    }

                });

                /**
                 * 进入预览界面
                 */
                mImageView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setClass(mContext, ImageChooserPreviewAndCheckActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("data", (Serializable) mImgs);
                        bundle.putInt("image_index", position);
                        bundle.putInt("choosenCount", choosenCount);
                        bundle.putInt("maxCount", maxCount);
                        intent.putExtras(bundle);
                        startActivityForResult(intent, ImageChooserPreviewAndCheckActivity.requestCode);
                    }
                });
                /**
                 * 已经选择过的图片，显示出选择过的效果
                 */

                if (item.isChecked) {
                    mSelect.setImageResource(R.drawable.image_chooser_checked);
                    mImageView.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
                } else {
                    mSelect.setImageResource(R.drawable.image_chooser_dir_unchecked);
                    mImageView.setColorFilter(Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
                }
            }
        };
        mGirdView.setAdapter(beanAdapter);
    }

    private void initListener() {
        mBottomLy.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mListImageDirPopupWindow.setAnimationStyle(R.style.anim_popup_from_bottom);
                if (mImgDir != null) {
                    mListImageDirPopupWindow.setDirSelected(mImgDir.getPath());
                }
                mListImageDirPopupWindow.showAsDropDown(mBottomLy, 0, 0);
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = .3f;
                getWindow().setAttributes(lp);
            }
        });
        ok.setOnClickListener(this);
        back.setOnClickListener(this);
        mToPreview.setOnClickListener(this);
    }

    /**
     * 图片被选中
     */
    private void itemImgSelected(final String jo, final ImageView mImageView, final ImageView mSelect, final int position) {
        // 已经选择过该图片
        if (mImgs.get(position).isChecked) {
            mImgs.get(position).isChecked = false;
            mSelect.setImageResource(R.drawable.image_chooser_dir_unchecked);
            mImageView.setColorFilter(Color.LTGRAY, PorterDuff.Mode.MULTIPLY);
            choosenCount--;
            mSelectedImage.remove(jo);
        } else {
            if (choosenCount + 1 > maxCount) {
                Toast.makeText(this, "最多选择" + maxCount + "张图片", Toast.LENGTH_LONG);
                return;
            }
            mImageView.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
            mImgs.get(position).isChecked = true;
            mSelectedImage.add(jo);
            mSelect.setImageResource(R.drawable.image_chooser_checked);
            choosenCount++;
        }
        ok.setText(String.format(getResources().getString(R.string.choose_pic), choosenCount, maxCount));
        toggleIcon(mSelectedImage);
    }

    /**
     * 为View绑定数据
     */
    private void data2View() {
        if (totalCount == 0) {
            Toast.makeText(getApplicationContext(), "一张图片都没有", Toast.LENGTH_SHORT).show();
            return;
        }
        mImgs = mAllFiles; //Arrays.asList(mMaxFiles);
        beanAdapter.clear();
        beanAdapter.addAll(mImgs);
        mImageCount.setText(totalCount + "张");
    }

    /**
     * 初始化展示文件夹的popupWindw
     */
    private void initListDirPopupWindw() {
        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        int mScreenHeight = outMetrics.heightPixels;
        mListImageDirPopupWindow = new ListImageDirPopupWindow(LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7), mImageFloders, LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.img_chooser_list_dir, null));
        mListImageDirPopupWindow.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        // 设置选择文件夹的回调
        mListImageDirPopupWindow.setOnImageDirSelected(this);
    }

    /**
     * 查询媒体文件夹
     */
    private void getImages() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }
        // 显示进度条
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");
        mAllFiles = new ArrayList<>();
        boolean success = PermissionCheckUtils.checkReadExternalPermission(ImageChooserActivity.this, "此操作需要读取sd卡上的数据，请授权",
                REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        if (success) {
            requestScan();
        }

    }

    private void requestScan() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = ImageChooserActivity.this.getContentResolver();
                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?", new String[]{
                                "image/jpeg", "image/png"},
                        " date_modified desc");
                if (mCursor == null) {
                    mHandler.sendEmptyMessage(0x110);
                    return;
                }
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    if (firstImage == null)
                        firstImage = path;
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    final String dirPath = parentFile.getAbsolutePath();

                    ImagePreviewBean bean = new ImagePreviewBean();
                    bean.url = path;
                    mAllFiles.add(bean);
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    }
                    ImageFloder imageFloder;
                    String[] fs = parentFile.list(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg")) {
                                return true;
                            }
                            return false;
                        }
                    });
                    int picSize = 0;
                    if (fs != null) {
                        picSize = fs.length;
                    }

                    if (!mDirPaths.contains(dirPath)) {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new ImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                        imageFloder.setCount(picSize);
                        mImageFloders.add(imageFloder);
                    }

                }
                totalCount += mCursor.getCount();
                mCursor.close();
                mDirPaths = null;
                mHandler.sendEmptyMessage(0x110);
            }
        }
        ).start();
    }

    /**
     * 初始化View
     */
    private void initView() {
        mGirdView = (GridView) findViewById(R.id.id_gridView);
        mChooseDir = (TextView) findViewById(R.id.id_choose_dir);
        mImageCount = (TextView) findViewById(R.id.id_total_count);
        mBottomLy = (RelativeLayout) findViewById(R.id.id_bottom_ly);
        ok = (Button) findViewById(R.id.ok);
        back = findViewById(R.id.back);
        mToPreview = (TextView) findViewById(R.id.to_preview);
        toggleIcon(mSelectedImage);
    }

    /**
     * @param list
     * @return void
     * @Description: 预览按钮样式
     * @throw Update by livvy at 20160517 : 预览时不显示预览的数量
     */
    private void toggleIcon(ArrayList<String> list) {
        String txt = "预览";
        if (list == null || list.size() == 0) {
            mToPreview.setTextColor(Color.GRAY);
        } else {
            mToPreview.setTextColor(Color.WHITE);
//			txt += "(" + list.size() + ")";
        }
        mToPreview.setText(txt);
    }

    /**
     * 选中文件夹
     *
     * @param floder
     */
    @Override
    public void selected(ImageFloder floder) {
        mImgDir = new File(floder.getDir());
        mImgs.clear();
        mImgDir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String filename) {
                if (filename.endsWith(".jpg") || filename.endsWith(".png") || filename.endsWith(".jpeg")) {
                    ImagePreviewBean bean = new ImagePreviewBean();
                    bean.url = dir.getAbsolutePath() + "/" + filename;
                    mImgs.add(bean);
                    return true;
                }
                return false;
            }
        });
        beanAdapter.clear();
        beanAdapter.addAll(mImgs);
        beanAdapter.notifyDataSetChanged();
        mImageCount.setText("共" + floder.getCount() + "张");
        mChooseDir.setText(floder.getName());
        mListImageDirPopupWindow.dismiss();

    }

    /**
     * @return void
     * @Description: 预览
     * @throw
     */
    private void toPreview() {
        if (mSelectedImage != null && mSelectedImage.size() <= 0) {
            return;
        }
        Intent intent = new Intent();
        intent.setClass(this, ImageChooserPreview.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", mSelectedImage);
        intent.putExtras(bundle);
        startActivityForResult(intent, ImageChooserPreview.requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageChooserPreviewAndCheckActivity.requestCode && data != null) {
            if (resultCode == ImageChooserPreviewAndCheckActivity.resultCode) {
                // 返回结果
                if (data.getSerializableExtra("result") == null) {
                    return;
                }
                mImgs = (List<ImagePreviewBean>) data.getSerializableExtra("result");
                choosenCount = data.getIntExtra("choosenCount", 0);
                mSelectedImage.clear();
                for (ImagePreviewBean item : mImgs) {
                    if (item.isChecked) {
                        mSelectedImage.add(item.url);
                    }
                }
                if (choosenCount == 0) {
                    choosenCount = mSelectedImage.size();
                }
                ok.setText(String.format(getResources().getString(R.string.choose_pic), choosenCount, maxCount));
                beanAdapter.notifyDataSetChanged();
            } else if (resultCode == ImageChooserPreviewAndCheckActivity.resultCodeOk) {
                // 返回结果
                if (data.getSerializableExtra("result") == null) {
                    return;
                }
                mImgs = (List<ImagePreviewBean>) data.getSerializableExtra("result");
                mSelectedImage.clear();
                for (ImagePreviewBean item : mImgs) {
                    if (item.isChecked) {
                        mSelectedImage.add(item.url);
                    }
                }
                ok();
            }
        }
    }

    @Override
    public void onDestroy() {
        mHandler.removeMessages(0);
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
    }

    /**
     * 返回
     */
    public void back() {
        finish();
    }

    /**
     * 点击确定
     */
    public void ok() {
        if (mSelectedImage.size() <= 0) {
            finish();
        } else {
            Intent intent = getIntent();
            intent.putExtra(requestCodeKey, (Serializable) mSelectedImage);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ok:
                ok();
                break;
            case R.id.back:
                back();
                break;
            case R.id.to_preview:
                toPreview();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                requestScan();
            } else {
                finish();
            }
        }
    }
}
